package app

import (
	"APT/internal/dao"
	"APT/internal/model/entity"
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/frame/g"

	"github.com/gogf/gf/v2/errors/gerror"

	"APT/api/app/basics"
)

func (c *ControllerBasics) ChannelFxCenter(ctx context.Context, req *basics.ChannelFxCenterReq) (res *basics.ChannelFxCenterRes, err error) {
	var (
		PmsAppStay []*entity.PmsAppStay
		MemberInfo *entity.PmsMember
		Channel    *entity.PmsChannel
	)
	res = new(basics.ChannelFxCenterRes)
	if err = dao.PmsMember.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsMember.Columns().ChannelId:  req.ChannelId,
		dao.PmsMember.Columns().RebateMode: "CHANNEL",
	}).Scan(&MemberInfo); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(MemberInfo) {
		err = gerror.New("会员信息不存在")
		return
	}
	if err = dao.PmsChannel.Ctx(ctx).Where(dao.PmsChannel.Columns().Id, req.ChannelId).Scan(&Channel); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(Channel) {
		err = gerror.New("渠道信息不存在")
		return
	}
	res.AllBrokerage = Channel.AllBalance
	res.Brokerage = Channel.Balance
	if err = dao.PmsAppStay.Ctx(ctx).Where(dao.PmsAppStay.Columns().Referrer, MemberInfo.Id).Page(1, 4).Scan(&res.BrokerageList); err != nil && !errors.Is(err, sql.ErrNoRows) {
		err = gerror.New("计算单数据异常")
		return
	}
	for k, v := range res.BrokerageList {
		if v.RebateStatus == "WAIT" {
			res.BrokerageList[k].RebateAmount += v.OrderAmount * (v.RebateRate / 100)
		}
	}
	// 结算中
	if err = dao.PmsAppStay.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsAppStay.Columns().Referrer:     MemberInfo.Id,
		dao.PmsAppStay.Columns().RebateStatus: "WAIT",
	}).Scan(&PmsAppStay); err != nil && !errors.Is(err, sql.ErrNoRows) {
		err = gerror.New("计算单数据异常")
		return
	}
	for _, v := range PmsAppStay {
		if v.RebateStatus == "WAIT" {
			res.SettlingBrokerage += v.OrderAmount * (v.RebateRate / 100)
		} else if v.RebateStatus == "SUCCESS" {
			//res.SettlingWithdraw += v.RebateAmount
		}
	}

	// 提现中金额
	res.SettlingWithdraw = Channel.ApplyWithdrawBalance
	// 已提现金额
	res.Withdraw = Channel.WithdrawBalance

	/*if res.SettlingWithdraw, err = dao.PmsWithdraw.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsWithdraw.Columns().ChannelId:      req.ChannelId,
		dao.PmsWithdraw.Columns().WithdrawStatus: "WAIT",
	}).Sum(dao.PmsWithdraw.Columns().WithdrawAmount); err != nil {
		err = gerror.New("计算单数据异常")
		return
	}*/
	return
}
